<template>
  <div class="countdown">
    <span class="number day">{{ d }}</span>
    <span class="colon unit-day">{{ separator == 'colon' ? ':' : '天' }}</span>
    <span class="number hour">{{ h }}</span>
    <span class="colon unit-hour">{{ separator == 'colon' ? ':' : '时' }}</span>
    <span class="number minute">{{ i }}</span>
    <span class="colon unit-minute">{{ separator == 'colon' ? ':' : '分' }}</span>
    <span class="number second">{{ s }}</span>
    <span v-if="separator == 'zh'" class="colon unit-second">{{
      separator == 'colon' ? ':' : '秒'
    }}</span>
  </div>
</template>

<script>
export default {
  props: {
    // 倒计时的时间，秒为单位
    timestamp: {
      type: [Number, String],
      default: 0
    },
    // 用英文冒号(colon)或者中文(zh)当做分隔符，false的时候为中文，如："11:22"或"11时22秒"
    separator: {
      type: String,
      default: 'colon'
    }
  },
  data() {
    return {
      d: '00', // 天的默认值
      h: '00', // 小时的默认值
      i: '00', // 分钟的默认值
      s: '00', // 秒的默认值
      timer: null,
      seconds: 0
    }
  },
  mounted() {
    // 如果自动倒计时
    this.timestamp && this.start()
  },
  methods: {
    // 倒计时
    start() {
      // 避免可能出现的倒计时重叠情况
      this.clearTimer()
      if (this.timestamp <= 0) return
      this.seconds = Number(this.timestamp)
      this.formatTime(this.seconds)
      this.timer = setInterval(() => {
        this.seconds--
        // 发出change事件
        this.$emit('change', this.seconds)
        if (this.seconds < 0) {
          return this.end()
        }
        this.formatTime(this.seconds)
      }, 1000)
    },
    // 格式化时间
    formatTime(seconds) {
      // 小于等于0的话，结束倒计时
      seconds <= 0 && this.end()
      let [day, hour, minute, second] = [0, 0, 0, 0]
      day = Math.floor(seconds / (60 * 60 * 24))
      // 判断是否显示“天”参数，如果不显示，将天部分的值，加入到小时中
      // hour为给后面计算秒和分等用的(基于显示天的前提下计算)
      hour = Math.floor(seconds / (60 * 60)) - day * 24
      // showHour为需要显示的小时
      let showHour = null
      showHour = hour
      minute = Math.floor(seconds / 60) - hour * 60 - day * 24 * 60
      second = Math.floor(seconds) - day * 24 * 60 * 60 - hour * 60 * 60 - minute * 60
      // 如果小于10，在前面补上一个"0"
      showHour = showHour < 10 ? '0' + showHour : showHour
      minute = minute < 10 ? '0' + minute : minute
      second = second < 10 ? '0' + second : second
      day = day < 10 ? '0' + day : day
      this.d = day
      this.h = showHour
      this.i = minute
      this.s = second
    },
    // 停止倒计时
    end() {
      this.clearTimer()
      this.$emit('end')
    },
    // 清除定时器
    clearTimer() {
      if (this.timer) {
        // 清除定时器
        clearInterval(this.timer)
        this.timer = null
      }
    }
  },
  beforeDestroy() {
    clearInterval(this.timer)
    this.timer = null
  }
}
</script>

<style></style>
